/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package util;

import common.Constant;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author root
 */
public class Util {
      /**
     * MD5加密key
     */
    public static String hashKeyForDisk(String key) {
        String cacheKey;
        try {
            final MessageDigest mDigest = MessageDigest.getInstance("MD5");
            mDigest.update(key.getBytes());
            cacheKey = bytesToHexString(mDigest.digest());
        } catch (NoSuchAlgorithmException e) {
            cacheKey = String.valueOf(key.hashCode());
        }
        return cacheKey;
    }

    private static String bytesToHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(0xFF & bytes[i]);
            if (hex.length() == 1) {
                sb.append('0');
            }
            sb.append(hex);
        }
        return sb.toString();
    }

    /**
     * 手机号码验证
     *
     */
    public static boolean isMobileNO(String mobiles) {
        /*
    移动：134、135、136、137、138、139、150、151、157(TD)、158、159、187、188
    联通：130、131、132、152、155、156、185、186
    电信：133、153、180、189、（1349卫通）
    总结起来就是第一位必定为1，第二位必定为3或5或8，其他位置的可以为0-9
         */
        String telRegex = "[1][358]\\d{9}";
        //"[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
        if (mobiles == null || mobiles.equals("")) {
            return false;
        } else {
            return mobiles.matches(telRegex);
        }
    }

    /**
     * 发送短信 信息
     * @param phone     目标电话
     * @param random    验证码
     * @return 
     */
    public static String sendSMS(String phone, String random) {
        String httpArg = "name="+Constant.SMSNAME+"&pwd="+Constant.SMSPWD;
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(httpArg);
        String tmp="由CY开发的手机APP体验系统 : 验证码是"+random+"【LHDF】";
        System.out.println("tmp=="+tmp);
        try {
            httpArg = "&content=" + URLEncoder.encode(tmp, "utf-8")+"&mobile="+phone;
            stringBuilder.append(httpArg);
            stringBuilder.append("&stime=&sign=&type=pt&extno=");
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex);
        }
        httpArg = stringBuilder.toString();
        System.out.println("sendSMS=="+httpArg);
        BufferedReader reader = null;
        String httpUrl = Constant.SMSURLHOST;
        String result = null;
        StringBuilder sbf = new StringBuilder();
        httpUrl = httpUrl + "?" + httpArg;
        try {
            URL url = new URL(httpUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setReadTimeout(5000);
            connection.setDoInput(true);
            connection.connect();
            InputStream is = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sbf.append(strRead);
                sbf.append("\r\n");
            }
            reader.close();
            result = sbf.toString();
            System.out.println("发送返回 sendSMS："+result);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("发送返回 sendSMS  false：");
        }
        return result;
    }
    
    
    //由@开发的手机APP体验系统 : 验证码是@【LHDF】
    //由@开发的手机APP体验系统 : 验证码是@【LHDF】
    public static String sendSMS2(String phone, String random) {
        String httpArg = "";
//        String tmp="由陈禹开发的 手机APP 测试 系统 : "+random; 
        String tmp="由陈禹开发的手机APP体验系统 : 验证码是"+random+"【LHDF】";
        System.out.println("tmp2=="+tmp);
        try {
            httpArg = "content=" + URLEncoder.encode(tmp, "utf-8")+"&mobile="+phone;
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex);
        }
        System.out.println(httpArg);
        BufferedReader reader = null;
        String httpUrl = Constant.SMSURLHOST;

        String result = null;
        StringBuilder sbf = new StringBuilder();

        try {
            URL url = new URL(httpUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setReadTimeout(5000);
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
            connection.setRequestProperty("name", "dxw13811614081");
            connection.setRequestProperty("pwd", "73F1527ABF71121E6DA8EACE4C22");
            connection.setRequestProperty("content", URLEncoder.encode(tmp, "utf-8"));
            connection.setRequestProperty("mobile", phone);
            connection.connect();
            InputStream is = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sbf.append(strRead);
                sbf.append("\r\n");
            }
            reader.close();
            result = sbf.toString();
            System.out.println("发送返回："+result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
